package com.ltu.timkor6.gamesite.games.missingbits.server;

import java.util.Date;

import com.ltu.timkor6.gamesite.games.missingbits.client.MissingBitsService;
import com.ltu.timkor6.gamesite.games.missingbits.shared.Question;
import com.ltu.timkor6.gamesite.server.DataBaseConnection;
import com.ltu.timkor6.gamesite.server.GameSiteServiceImpl;
import com.ltu.timkor6.gamesite.shared.Result;

@SuppressWarnings("serial")
public class MissingBitsServiceImpl extends GameSiteServiceImpl implements MissingBitsService
{
	private Result result;
	private Question question;
		
	private int questionNumber;
	
	public MissingBitsServiceImpl()
	{
		this.result = new Result();
		this.result.setGameTitle("MissingBits");
	}
	
	/**
	 * First time, starting game.
	 */
	public Question start(int questions)
	{
		this.result.setTurns(questions);
		
		this.questionNumber = 0;
		
		return question();
	}
	
	/**
	 * Create a question.
	 */
	public Question question()
	{
		this.questionNumber++;
		this.question = new Question();
		this.question.setQuestionNumber(questionNumber);
		this.question.setStartTime(new Date());
		
		CreateQuestion cq = new CreateQuestion(this.question);
		
		return cq.getQuestion();
	}
	
	/**
	 * Check an answer and return given points.
	 */
	public int answer(String value)
	{
		int points = 0;
		if(value.length() == 0)
		{
			value = "0";
		}
		try
		{
			int answer = Integer.parseInt(value);
			if(answer == question.getResult())
			{
				points = givePoints();
			}
			
			if(result.getTurns() <= questionNumber && userInfo != null)
			{
				new DataBaseConnection(this).addResult(result);
			}
			
			return points;
		}
		catch(NumberFormatException e)
		{
			
		}
		
		return 0;
	}
	
	/**
	 * Return the result.
	 */
	public Result result()
	{
		return result;
	}
	
	/**
	 * Calculate points.
	 * @return
	 */
	private int givePoints()
	{
		int points = 10;
		
		this.result.addPoints(points);
		
		return points;
	}
}
